package com.ktgj.pay.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ktgj.pay.domain.*;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class BaseUtil {
	
	/**
	   * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
	   * 
	   * @param strDate
	   * @return
	   */
	public static Date strToDateLong(String strDate) {
	   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	   ParsePosition pos = new ParsePosition(0);
	   Date strtodate = formatter.parse(strDate, pos);
	   return strtodate;
	}
	/**
	 * 将长时间转换为指定样式的字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dateToString(Long date,String format){
		Date now = new Date(date);
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);//可以方便地修改日期格式
		String hehe = dateFormat.format( now ); 
		return hehe;
		
	}
	
	
	/**
	 * 根据指定格式，返回系统时间
	 * @param format
	 * @return
	 */
	public static String getDateString(String format){
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);//可以方便地修改日期格式
		String hehe = dateFormat.format( now ); 
		return hehe;
	}

	/**
	 * 返回参数外层包装
	 * @param obj
	 * @return
	 */
	public static String PackagingReturn(String obj){
		return "<![CDATA[" + obj + "]]>";
	}
	/**
	 * 包装xml请求头部
	 * @param obj
	 * @return
	 */
	public static String PackagingInterFace(String obj){
		return "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<invInterface>" + obj + "</invInterface>";
	}
	/**
	 * 包装基础请求信息
	 * @param baseInfo
	 * @return
	 */
	public static String PackagingBaseInfo(MoBaseInfo baseInfo){
		String resString = "<baseInfo>"
				+ "<version>"+baseInfo.getVersion()+"</version>" 
				+ "<interfaceCode>"+baseInfo.getInterfaceCode()+"</interfaceCode>"
				+ "<sellerTaxNo>"+baseInfo.getSellerTaxNo()+"</sellerTaxNo>"
				+ "</baseInfo>" ;
		return resString;
	}
	/**
	 * 包装外层请求返回
	 * @return
	 */
	public static String PackagingReInfo(){
		return "<returnInfo>"
				+ "<returnCode></returnCode>"
				+ "<returnMessage></returnMessage>"
				+ "</returnInfo>";
	}
	
	public static String PackagingEXData(String info){
		/*
		 * zipCode : (0,1根据数据包大小判断是否进行压缩)
		 * encryptCode : 加密方式代码，0表示不用任何加密,1:AES加密
		 */
		String result = "<exData>"
				+ "<zipCode>0</zipCode>"
				+ "<encryptCode>0</encryptCode>"
				+ "<content>"+info+"</content>"
				+ "</exData>";
				
		return result;
	}
	/**
	 * base64编码
	 * @param result
	 * @return
	 */
	public static String Encoded(String result){
		//base64字符串
		String base64String = "";
		try {
			//String --> byte[]
			byte[] data = result.getBytes("utf-8");
			//编码
			base64String = DatatypeConverter.printBase64Binary(data);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return base64String;
	}
	/**
	 * base64解码
	 * @param result
	 * @return
	 */
	public static String Decide(String result){
		//解码后字符串
		String str = "";
		//解码
		byte[] base64data = DatatypeConverter.parseBase64Binary(result);
		
		try {
			//byte[] --> String 
			str = new String(base64data,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
	/**
	 * 包装返回接口调用结果
	 * @param response
	 * @param object
	 * @return
	 */
	public static MoInterfaceResponse getResponse(MoResponse response, Object object){
		MoInterfaceResponse interfaceResponse = new MoInterfaceResponse();
		interfaceResponse.setVersion(response.getBaseInfo().getVersion());
		interfaceResponse.setInterfaceCode(response.getBaseInfo().getInterfaceCode());
		interfaceResponse.setReturnCode(response.getReturnInfo().getReturnCode());
		interfaceResponse.setReturnMessage(response.getReturnInfo().getReturnMessage());
		interfaceResponse.setZipCode(response.getExData().getZipCode());
		interfaceResponse.setEncryptCode(response.getExData().getEncryptCode());
		interfaceResponse.setMethodReturnInfo(object);
		return interfaceResponse;
	}
	/**
	 * 包装返回请求Xml字符串
	 * @param methodName
	 * @param context
	 * @return
	 */
	public static String returnRequestString(String methodName, String context,String sellerTaxNo){
		MoBaseInfo baseInfo = new MoBaseInfo();
		baseInfo.setInterfaceCode(methodName);
		baseInfo.setSellerTaxNo(sellerTaxNo);
		baseInfo.setVersion("1.0");
		
		String result = BaseUtil.PackagingBaseInfo(baseInfo);
		result = result + BaseUtil.PackagingReInfo();
		result = result + BaseUtil.PackagingEXData(context);
		result = BaseUtil.PackagingInterFace(result);
		result = BaseUtil.PackagingReturn(result);
		return result;
	}
	
	/**
	 * 队列发送
	 * routingKey：队列名称-配置名称
	 * resultJson：队列消息-Json格式
	 * @throws InterruptedException 
	 */
	public static void SendRabbitMQ(String routingKey,String resultJson) throws InterruptedException {
		ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext("spring\\spring-rabbitmq.xml");
	    AmqpTemplate amqpTemplate = appCtx.getBean("amqpTemplate", AmqpTemplate.class);
	    //给队列发送消息
	    amqpTemplate.convertAndSend(routingKey,resultJson);
	    
	    // 休眠1秒
        Thread.sleep(1000);
	    
	    //容器销毁
//	    appCtx.destroy();
        appCtx.close();//关闭
	}
	/**
	 * 发送消息-Json封装
	 * @param mq
	 * @return
	 */
	public static String RabbitMQJson(MoReceiveRabbitMQ mq){
		String Json = "{"
				+ "\"methodName\": \""+mq.getMethodName()+"\","
				+ "\"selectKey\": \""+mq.getSelectKey()+"\","
				+ "\"tipsMessage\": \""+mq.getTipsMessage()+"\""
				+ "}";
		return Json;
	}
	
	/**
	 * 指数退避算法
	 * @param n
	 */
	public static void reTry(int n,MoReceiveRabbitMQ mq){
		int max = twoPowerK(n)-1;
//		System.out.println("产生的集合为[0..."+max+"]");
		//随机了一个值
		Random random = new Random();
		int r = random.nextInt(max);
//		System.out.println("随机值为"+r*10+"睡眠"+r*10+"秒");
		try {
			Thread.sleep(r*1000);
			String resultJson = RabbitMQJson(mq);
			SendRabbitMQ(mq.getMethodName(), resultJson);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static int twoPowerK(int k){
		int a = 2;
		int f = 1;
		for(int i = k; i > 0; i--){
			f *= a;
		}
		return f;
	}
	
	
	public static void main(String[] args){
//		int n = 1;
//		while (true) {
//			if(n < 5){
//				reTry(n);
//				n++;
//				System.out.println("第"+n+"次");
//			}else{
//				break;
//			}
//			
//		}
	}
	
	public static MoSendSMS getSendSMS(String Json){
		MoSendSMS sendSMS = new MoSendSMS();
		JSONObject JSR = JSONObject.parseObject(Json);
		sendSMS.setMobile(JSR.getString("Mobile"));
		sendSMS.setContents(JSR.getString("Contents"));
		if(RegexUtil.isNotNull(JSR.getString("Key"))){
			sendSMS.setKey(JSR.getString("Key"));
		}else{
			sendSMS.setKey("");
		}
		if(RegexUtil.isNotNull(JSR.getString("OrderID"))){
			sendSMS.setOrderID(JSR.getString("OrderID"));
		}else{
			sendSMS.setOrderID("");
		}
		sendSMS.setSendCompany(JSR.getInteger("SendCompany"));
		sendSMS.setSmsLevel(JSR.getInteger("SmsLevel"));
		sendSMS.setSmsSouce(JSR.getInteger("SmsSouce"));
		return sendSMS;
	}
	/**
	 * 发票余量提醒-短信批量通知
	 * @param Contents
	 */
	public static void sendSmsToAdmin(String Contents){
		/*
		 * 需通知的手机号
		 * 13681437841；13683014025；15600525329；15011314323；15611582696；17710168801
		 */
		String[] admins = InterfaceUrl.SMS_ADMINS.split(",");
		for(int i = 0; i < admins.length; i++){
			String mobile = admins[i];
			MoSendSMS sendSMSModel = new MoSendSMS();
			sendSMSModel.setMobile(mobile);
			sendSMSModel.setContents(Contents);
			sendSMSModel.setSmsSouce(3);
			sendSMSModel.setSendCompany(1);
			sendSMSModel.setSmsLevel(2);
			sendSMSModel.setKey("");
			sendSMSModel.setOrderID("");
			ResponseModel model = sendSMS(sendSMSModel);
			System.out.println("---"+i+"---"+admins[i]+"---"+model.getMessage());
		}
		
	}
	
	
	public static ResponseModel sendSMS(MoSendSMS sendSMS){
		ResponseModel model = new ResponseModel();
		String requestJson = getSendSMSJson(sendSMS);
		String responseBody = OkHttpNanoUtils.sendPostJson(InterfaceUrl.SMS_API, requestJson);
		JSONObject JSR = JSONObject.parseObject(responseBody);
		if(JSR.getInteger("code") == 0){
			Log4j.addLog("短信调用sendSMS-发送成功", requestJson, responseBody);
			model.setSuccess(true);
			model.setMessage("短信发送成功");
		}else{
			Log4j.addLog("短信调用sendSMS-发送失败", requestJson, responseBody);
			model.setSuccess(false);
			model.setMessage("短信发送失败");
		}
		return model;
	}
	

	public static String getSendSMSJson(MoSendSMS sendSMS){
		String jsonString = "{\"SmsDto\": {"
				+ "\"Mobile\": \""+sendSMS.getMobile()+"\","
				+ "\"Contents\": \""+sendSMS.getContents()+"\","
				+ "\"Key\": \""+sendSMS.getKey()+"\","
				+ "\"SmsLevel\": "+sendSMS.getSmsLevel()+","
				+ "\"SmsSouce\": "+sendSMS.getSmsSouce()+","
				+ "\"SendCompany\": "+sendSMS.getSendCompany()+","
				+ "\"OrderID\": \""+sendSMS.getOrderID()+"\","
				+ "\"CallBackUrl\": null,"
				+ "\"OpEmployeeID\": 0,"
				+ "\"ReadySendTime\": null,"
				+ "\"SmsID\": 0,"
				+ "\"UpCallBackUrl\": \"\","
				+ "\"ParentSmsId\": 0}"
				+ "}";
		return jsonString;
	}
	
	
	public static TickInvoiceInfo[] getTickInvoiceInfos(JSONArray array){ 
		TickInvoiceInfo[] tickInvoiceInfos = new TickInvoiceInfo[array.size()];
		for(int a = 0; a < array.size(); a++){
			JSONObject object = array.getJSONObject(a);
			TickInvoiceInfo info = new TickInvoiceInfo();
			info.setGuestID(object.getString("GuestID"));
			info.setInvoiceStatus(object.getString("InvoiceStatus"));
			info.setOrderId(object.getString("OrderId"));
			tickInvoiceInfos[a] = info;
		}
		return tickInvoiceInfos;
	}
	
	
	
}
